/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var TgDesignPcModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //`pc_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  //`page_id` bigint(20) unsigned NOT NULL COMMENT '模板页ID',
  //`pc_index` int(3) NOT NULL DEFAULT '0' COMMENT '下标（0开始）',
  //`backup_flg` int(1) NOT NULL DEFAULT '0' COMMENT '0普通页; 1保留页',
  //`data` mediumtext COMMENT '模版页内容',
  //`replaces` mediumtext COMMENT '可替换组',
  //`hash_tag` varchar(100) DEFAULT '0' COMMENT '标记',
  //`thumb_s` text COMMENT '缩略图小',
  //`thumb_m` text COMMENT '缩略图中',
  //`thumb_l` text COMMENT '缩略图大',
  //`audio` text COMMENT '音频url数组',
  //`video` text COMMENT '视频url数组',
  //`media` text COMMENT '原始视频',
  //`dirty` int(1) NOT NULL DEFAULT '0' COMMENT '0未修改; 1页被修改过',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0',

};
TgDesignPcModel.prototype = new ItbBaseModel();

// 取得表名
TgDesignPcModel.prototype.getTableName = function(){
    return 'tg_design_pc';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
TgDesignPcModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'pc_id='+this.pc_id;
}

// 取得排序方法（需要各派生类进行重载）
TgDesignPcModel.prototype.getOrderBy = function(){
    return ' pc_index asc ';
}

//------------------------------------------------------------------
/* 获取分页pc信息
 * 参数:design_id/page_id/pc_id
 * 参数:callback:回调
 * */
TgDesignPcModel.prototype.getPcInfoById = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' select t.pc_id, t.design_id, t.page_id, t.pc_index, t.backup_flg, '+
            ' t.data, t.replaces, t.hash_tag, t.thumb_s, t.thumb2, t.dirty, pg.page_index '+
            ' from TG_DESIGN_PC t, TG_DESIGN_PAGE pg'+
            ' where t.del_flg = 0 AND pg.del_flg=0 AND t.page_id=pg.page_id ';
        if(THIS.design_id){
            sql += ' and t.design_id = '+ THIS.design_id;
        }
        if(THIS.page_id){
            sql += ' and t.page_id = '+ THIS.page_id;
        }
        if(THIS.pc_id){
            sql += ' and t.pc_id = '+ THIS.pc_id;
        }
        sql += ' order by t.design_id, pg.page_index, t.pc_index ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            callback(error, result);
        });
    });
}
//--------------------------------end-------------------------------

//------------------------------------------------------------------
/* 获取分页信息(按page为单位)
 * 参数:design_id/page_id
 * 参数:callback:回调
 * */
TgDesignPcModel.prototype.getPageAndPcInfo = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' select t.pc_id, t.pc_index, t.page_id, p.page_index, t.design_id, '+
            ' p.backup_flg AS page_backup_flg, t.data AS pc_data, p.data AS page_data '+
            ' from TG_DESIGN_PAGE p, TG_DESIGN_PC t '+
            ' where p.del_flg = 0 and t.del_flg = 0 '+
            ' and p.page_id = t.page_id and p.design_id = t.design_id ';
        if(THIS.design_id){
            sql += ' and t.design_id = '+ THIS.design_id;
        }
        if(THIS.page_id){
            sql += ' and t.page_id = '+ THIS.page_id;
        }
        sql += ' order by t.design_id, p.page_index, t.pc_index ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();


            if(result && result.length>0) {
                var retInfo=[];

                var tmpArrPc=new Array();
                var tmpPage = result[0];

                for(var i in result) {
                    var item = result[i];

                    if(item.page_id != tmpPage.page_id) {
                        retInfo.push({
                            page_id: tmpPage.page_id,
                            page_index: tmpPage.page_index,
                            data: tmpPage.page_data,
                            pcData: tmpArrPc
                        });

                        tmpPage = result[i];
                        tmpArrPc = new Array();
                    }

                    tmpArrPc.push({
                        pc_id: result[i].pc_id,
                        pc_index: result[i].pc_index,
                        data: result[i].pc_data
                    });

                    if(i==result.length-1) {// 最后一条
                        retInfo.push({
                            page_id: tmpPage.page_id,
                            page_index: tmpPage.page_index,
                            data: tmpPage.page_data,
                            pcData: tmpArrPc
                        });
                    }
                }

                callback(error, retInfo);

            } else {
                callback(error, null);
            }
        });
    });
}
//--------------------------------end-------------------------------

//------------------------------------------------------------------
// 按page_index从小到大、pc_index从大到小排序,
// callback 参数：
//                error：错误
//                items：找到所有对象
TgDesignPcModel.prototype.findFromDBOrderByPageIndex = function(callback){
    var THIS = this;

    // 从mysql中查询
    pool.pool.getConnection(function(err, connection) {
        var sql = 'select a.*,b.page_index from tg_design_pc a,tg_design_page b  '+
            ' where a.design_id = '+THIS.design_id+
            ' and a.del_flg=0 '+
            ' and b.design_id= '+THIS.design_id+
            ' and b.del_flg=0 '+
            ' and a.page_id=b.page_id '+
            ' order by b.page_index asc ,a.pc_index asc ';

        // Use the connection
        connection.query(sql, function(error, items) {
            // And done with the connection.
            connection.release();

            // 回调
            callback(error, items);
        });

    });

}
//------------------------------------------------------------------

//------------------------------------------------------------------
/* 获取用户pc信息(包括design的thumb2信息)
 * 参数:doc_id
 * 参数:callback:回调
 * */
TgDesignPcModel.prototype.getPcInfoByUserDocId = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql = ' SELECT u.*, pg.page_index, t.thumb2 '+
            ' FROM TG_DESIGN_PC t, TG_USER_PAGE pg, TG_USER_PC u'+
            ' WHERE u.del_flg = 0 AND u.doc_id='+ THIS.doc_id+
            ' AND pg.del_flg = 0 AND pg.page_id=u.page_id '+
            ' AND t.del_flg = 0 AND t.pc_id=u.design_pc_id '+
            ' ORDER BY pg.page_index, u.pc_index ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            callback(error, result);
        });
    });
}

//------------------------------------------------------------------
/* 获取用户pc信息
 * 参数:doc_id
 * 参数:callback:回调，返回参数：
 *      error
 *      data，结构体包括如下属性：
 *              ver:版本号
 *              data:pc的data
 * */
TgDesignPcModel.prototype.getPcDataOfDesign = function(callback){
    var THIS = this;
    var tableName = this.getTableName();

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql =
        ' 			  select d.ver,c.data ,p.page_index '+
        '             from tg_design_doc d,  '+
        '             	tg_design_page p,  '+
        '             	tg_design_pc c  '+
        '             where d.design_id='+ THIS.design_id+
        '             and d.del_flg=0  '+
        '             and d.design_id=p.design_id  '+
        '             and p.del_flg=0  '+
        '             and d.design_id=c.design_id  '+
        '             and p.page_id=c.page_id '+
        '             and c.del_flg=0  '+
        '             order by p.page_index asc ';

        //var sqlValue = [THIS.type_id];
        //sql = mysql.format(sql, sqlValue);
        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();
            //console.log();

            callback(error, result);
        });
    });
}
//--------------------------------end-------------------------------

// 导出
module.exports = TgDesignPcModel;